<template>
  <div class="main-container">
    <!-- 进度条 -->
    <el-row>
      <el-col :span="24">
        <el-steps :active="currentStep" align-center finish-status="success">
          <el-step title="编辑"></el-step>
          <el-step title="初审"></el-step>
          <el-step title="审核"></el-step>
          <el-step title="批准"></el-step>
        </el-steps>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <h2 class="text-center">发票申请单</h2>
      </el-col>
    </el-row>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 客户和申请开票时间 显示视图 -->
    <el-row style="margin: 20px 0" v-if="!isEdit">
      <el-col :span="5" class="text-right"> 最终客户： </el-col>
      <el-col :span="3" class="text-left"> {{ application.customerFinal }} </el-col>
      <el-col :span="4" class="text-right"> 申请开票时间： </el-col>
      <el-col :span="3" class="text-left"> {{ application.invoicingDate }} </el-col>
      <el-col :span="3" class="text-right"> 工号： </el-col>
      <el-col :span="4" class="text-left"> {{ application.workingNumber }} </el-col>
    </el-row>
    <!-- 客户和申请开票时间 编辑视图 -->
    <el-row style="margin: 20px 0; height: 50px; line-height: 50px" v-else>
      <el-col :span="5" class="text-right"> 最终客户： </el-col>
      <el-col :span="3">
        <el-input v-model="cacheApplication.customerFinal"></el-input>
      </el-col>
      <el-col :span="4" class="text-right"> 申请开票时间： </el-col>
      <el-col :span="3">
        <el-date-picker v-model="cacheApplication.invoicingDate" type="date" placeholder="选择日期"> </el-date-picker>
      </el-col>
      <el-col :span="4" class="text-right"> 工号： </el-col>
      <el-col :span="3">
        <el-input v-model="cacheApplication.workingNumber"></el-input>
      </el-col>
    </el-row>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 按钮区域 -->
    <el-row>
      <el-col :span="24">
        <el-button-group class="btn5">
          <el-button type="primary" size="small" icon="el-icon-edit" @click="edit()"
            v-if="!isEdit && $checkAuth('发票申请编辑')">编辑</el-button>
          <el-button type="primary" size="small" icon="el-icon-check" @click="saveApplicationReq()"
            v-if="isEdit && $checkAuth('发票申请编辑')">保存</el-button>
          <el-button type="primary" size="small" icon="el-icon-close" @click="cancel()"
            v-if="isEdit && $checkAuth('发票申请编辑')">取消</el-button>
          <el-button type="primary" size="small" icon="el-icon-top" @click="pageViewChangeSubmit()"
            v-if="!isEdit && $checkAuth('发票申请编辑')">提交</el-button>
          <el-button type="primary" size="small" icon="el-icon-circle-check" @click="pageViewChangePreAudit()"
            v-if="!isEdit && $checkAuth('发票申请初审')">初审</el-button>
          <el-button type="primary" size="small" icon="el-icon-circle-check" @click="pageViewChangeAudit()"
            v-if="!isEdit && $checkAuth('发票申请审核')">审核</el-button>
          <el-button type="primary" size="small" icon="el-icon-circle-check" @click="pageViewChangeApproval()"
            v-if="!isEdit && $checkAuth('发票申请批准')">批准</el-button>
          <el-button type="primary" size="small" icon="el-icon-close" @click="closeApplication()"
            v-if="!isEdit && $checkAuth('发票申请编辑')">关闭</el-button>
          <el-button type="primary" size="small" icon="el-icon-position" @click="back" v-if="!isEdit">返回</el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <el-form>
      <el-form-item label="发票内容" class="form-label" style="margin: 5px 0; width: 98%"></el-form-item>
    </el-form>
    <!-- 发票抬头 显示视图-->
    <el-table v-if="!isEdit" style="width: 98%" :data="customer" :show-header="false" :span-method="mergeA"
      cell-class-name="cell-style">
      <el-table-column prop="key" label="key" align="center" min-width="350"> </el-table-column>
      <el-table-column prop="value" label="value" align="left" min-width="200">
        <template slot-scope="scope">
          <div class="pl30">{{ scope.row.value }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
    </el-table>
    <!-- 发票抬头 编辑视图-->
    <el-table v-if="isEdit" style="width: 98%" :data="customer" :show-header="false" :span-method="mergeA"
      cell-class-name="cell-style">
      <el-table-column prop="key" label="key" align="center" min-width="350"> </el-table-column>
      <el-table-column prop="value" label="value" align="left" min-width="200">
        <template slot-scope="scope">
          <el-autocomplete v-if="scope.row.key == '名称：'" class="w500" v-model="scope.row.value" clearable
            :fetch-suggestions="querySearch" @select="customerSelect"></el-autocomplete>
          <div class="pl30" v-else>{{ scope.row.value }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
    </el-table>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 发票项 显示视图 -->
    <el-table v-if="!isEdit" style="width: 98%" :data="application.itemList" header-cell-class-name="header-cell-style"
      cell-class-name="cell-style">
      <el-table-column prop="taxableServiceName" label="货物或应税劳务、服务名称" align="center" min-width="350"></el-table-column>
      <el-table-column prop="serviceSpecification" label="规格型号" align="center" min-width="200"></el-table-column>
      <el-table-column prop="unit" label="单位" align="center" width="100"> </el-table-column>
      <el-table-column prop="number" label="数量" align="center" width="100"> </el-table-column>
      <el-table-column prop="price" label="单价(含税)" align="right" header-align="center" width="100">
        <template slot-scope="scope"> {{ scope.row.price }} </template>
      </el-table-column>
      <el-table-column prop="amount" label="金额(含税)" align="right" header-align="center" width="120">
        <template slot-scope="scope"> {{ scope.row.amount }} </template>
      </el-table-column>
      <el-table-column prop="taxRate" label="税率" align="center" width="100">
        <template slot-scope="scope" v-if="scope.row.itemId != null"> {{ scope.row.taxRate * 100 }}% </template>
      </el-table-column>
      <el-table-column prop="taxMoney" label="税额" align="right" header-align="center" width="120">
        <template slot-scope="scope"> {{ scope.row.taxMoney }} </template>
      </el-table-column>
    </el-table>
    <!-- 发票项 编辑视图 -->
    <el-table v-if="isEdit" style="width: 98%" :data="cacheApplication.itemList"
      header-cell-class-name="header-cell-style" cell-class-name="cell-style">
      <el-table-column label="货物或应税劳务、服务名称" align="center" min-width="350">
        <template slot-scope="scope">
          <el-input v-model="scope.row.taxableServiceName"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="center" min-width="200">
        <template slot-scope="scope">
          <el-input v-model="scope.row.serviceSpecification"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位" align="center" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.unit"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.number" @change="numberChange(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价(含税)" align="center" width="100">
        <template slot-scope="scope"> {{ scope.row.price }} </template>
      </el-table-column>
      <el-table-column label="金额(含税)" align="center" width="120">
        <template slot-scope="scope">
          <el-input v-model="scope.row.amount" @change="amountChange(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="税率" align="center" width="100">
        <template slot-scope="scope"> {{ scope.row.taxRate * 100 }}% </template>
      </el-table-column>
      <el-table-column label="税额" align="center" width="120">
        <template slot-scope="scope"> {{ scope.row.taxMoney }} </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="120">
        <template slot-scope="scope">
          <el-button @click="removeItem(scope.$index)" type="text" size="small">删除</el-button>
          <el-button @click="insertItem(scope.$index)" type="text" size="small">添加</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 表格合计部分 -->
    <el-table style="width: 98%" :data="amounts" :show-header="false" :span-method="mergeB"
      cell-class-name="amount-cell-style">
      <el-table-column prop="titleU" label="titleU" align="center" min-width="350"> </el-table-column>
      <el-table-column prop="upper" label="upper" align="center" min-width="200"> </el-table-column>
      <el-table-column prop="titleL" label="titleL" align="center" width="100"> </el-table-column>
      <el-table-column prop="lower" label="lower" align="center" width="100"> </el-table-column>
      <el-table-column prop="amountTax" align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
      <el-table-column align="center" width="100"> </el-table-column>
      <el-table-column align="center" width="120"> </el-table-column>
      <el-table-column align="center" width="120" v-if="isEdit"> </el-table-column>
    </el-table>
    <div style="width: 98%; border-top: 1px solid black"></div>

    <!-- 发票申请备注 显示视图 -->
    <el-form v-if="!isEdit">
      <el-form-item label="发票备注" class="form-label" style="margin: 5px 0; width: 98%"></el-form-item>
      <el-form-item style="margin: 5px 0; width: 98%">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 10 }" v-model="application.fapiaoRemark"
          readOnly></el-input>
      </el-form-item>
    </el-form>
    <!-- 发票申请备注 编辑视图 -->
    <el-form v-if="isEdit">
      <el-form-item label="发票备注" class="form-label" style="margin: 5px 0; width: 98%"></el-form-item>
      <el-form-item style="margin: 5px 0; width: 98%">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 10 }"
          v-model="cacheApplication.fapiaoRemark"></el-input>
      </el-form-item>
    </el-form>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 办理记录部分 -->
    <el-form>
      <el-form-item label="审批记录" class="form-label" style="margin: 5px 0; width: 98%"></el-form-item>
    </el-form>
    <div>
      <el-table style="width: 98%" :data="application.handleList" border stripe class="custom-table">
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column label="业务" prop="handleName" align="center" width="120"></el-table-column>
        <el-table-column label="办理人" prop="handlerName" align="center" width="120"></el-table-column>
        <el-table-column label="办理时间" prop="createTime" align="center" width="250"></el-table-column>
        <el-table-column label="办理结论" prop="handleConclusion" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.handleConclusion ? '通过' : '未通过' }}
          </template>
        </el-table-column>
        <el-table-column label="下一环节" prop="next" align="center" width="120"></el-table-column>
        <el-table-column label="办理意见" prop="handleRemark" min-width="120"></el-table-column>
      </el-table>
    </div>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 提交初审部分 -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <el-dialog title="提交审批" :visible.sync="preDdialogVisible" width="35%" :close-on-click-modal="false"
      @close="closePreDialog">
      <el-form>
        <el-form-item label="初审人员" label-width="120px" prop="next">
          <el-select v-model="preAuditor" class="w200" placeholder="请选择初审人员" clearable filterable>
            <el-option v-for="item in userList" :key="item" :label="item" :value="item"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作备注" label-width="120px" prop="submitInput">
          <el-input class="w300" type="textarea" :row="3" v-model="submitInput"></el-input>
        </el-form-item>

        <el-form-item label-width="120px">
          <el-button type="primary" @click="submit">保存</el-button>
          <el-button @click="closePreDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <!-- 审核批准部分 -->
    <!-- ==================================================================================================== -->
    <!-- ==================================================================================================== -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="35%" :close-on-click-modal="false"
      @close="closeDialog">
      <el-form :model="handleResult">
        <el-form-item label="处理结论" label-width="120px" prop="handleConclusion">
          <el-select v-model="handleResult.handleConclusion" class="w200" placeholder="请选择审批结论" clearable filterable>
            <el-option label="--请选择--" :value="2"></el-option>
            <el-option label="通过" :value="1"></el-option>
            <el-option label="驳回" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="处理意见" label-width="120px" prop="handleRemark">
          <el-input class="w300" type="textarea" :row="5" v-model="handleResult.handleRemark"></el-input>
        </el-form-item>

        <el-form-item label-width="120px">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import _ from 'lodash'
import { Notification } from 'element-ui'
import { moneyToUpper } from './money-util'

import { getFapiaoHeaderApi } from '@/api/api_fapiao_header'
import {
  getFapiaoApplicationApi,
  saveFapiaoApplicationApi,
  submitFapiaoApplicationApi,
  preauditFapiaoApplicationApi,
  auditFapiaoApplicationApi,
  approvalFapiaoApplicationApi,
  closeFapiaoApplicationApi,
  createFapiaoApplicationApi
} from '@/api/api_fapiao_application'
import { getUserListApi } from '@/api/authority/api-authority'
@Component({
  components: {}
})
export default class Material extends Vue {
  // 发票申请数据对象
  application: any = {
    fapiaoId: 0
  }

  // 编辑状态下的缓存
  cacheApplication: any = {}

  // 当前流程状态
  currentStep: number = 0

  // 发票抬头列表
  headers: any = []

  // 发票抬头  显示数据对象
  customer: any = [
    { key: '名称：', value: '' },
    { key: '纳税人识别号：', value: '' },
    { key: '地址/电话：', value: '' },
    { key: '开户行及账号： ', value: '' }
  ]

  // 发票金额合计  显示数据对象
  amounts: any = [
    {
      titleU: '合计',
      upper: '',
      titleL: '',
      lower: '',
      amountTax: '0'
    },
    {
      titleU: '价税合计（大写）',
      upper: '零元整',
      titleL: '小写',
      lower: '0'
    }
  ]

  created() {
    // 获取发票抬头数据
    this.getHeaderListReq()
    // 判断是新建还是查看详情
    let type = this.$route.params['type']
    if (type == 'detail') {
      this.application.fapiaoId = this.$route.params['fapiaoId']
      this.getFapiaoApplicationReq()
    } else if (type == 'create') {
      this.createFapiaoApplicationReq()
    }
  }

  async getFapiaoApplicationReq() {
    await getFapiaoApplicationApi({ fapiaoId: this.application.fapiaoId }).then(res => {
      this.application = res.data
      if (this.application.state.string == '待提交' || this.application.state.string == '初审未通过') {
        this.currentStep = 0
      } else if (this.application.state.string == '待初审' || this.application.state.string == '审核未通过') {
        this.currentStep = 1
      } else if (this.application.state.string == '待审核' || this.application.state.string == '批准未通过') {
        this.currentStep = 2
      } else if (this.application.state.string == '待批准') {
        this.currentStep = 3
      } else {
        this.currentStep = -1
      }
      // 绑定发票抬头信息
      this.customerSelect(this.application.header)
      // 绑定发票合计信息
      this.amounts[0]['titleL'] = '￥' + this.application.amount.toFixed(2)
      this.amounts[0]['amountTax'] = '￥' + this.application.amountTax.toFixed(2)
      this.amounts[1]['upper'] = this.application.amountUpper
      this.amounts[1]['lower'] = '￥' + this.application.amount.toFixed(2)
      // 如果发票项不足5行，填补空白行
      if (this.application.itemList.length < 5) {
        let needEmpty = 5 - this.application.itemList.length
        for (let i = needEmpty; i > 0; i--) {
          let obj = {
            itemId: null,
            fapiaoId: null,
            taxableServiceName: null,
            serviceSpecification: null,
            serviceUnit: null,
            number: null,
            unit: null,
            price: null,
            amount: null,
            taxRate: 0.13,
            taxMoney: null
          }
          this.application.itemList.push(obj)
        }
      }
    })
  }

  async createFapiaoApplicationReq() {
    await createFapiaoApplicationApi({ fapiaoId: this.application.fapiaoId }).then(res => {
      this.application = res.data
      this.currentStep = 0
      // 绑定发票抬头信息
      this.customerSelect(this.application.header)
      // 绑定发票合计信息
      this.amounts[0]['titleL'] = '￥' + this.application.amount.toFixed(2)
      this.amounts[0]['amountTax'] = '￥' + this.application.amountTax.toFixed(2)
      this.amounts[1]['upper'] = this.application.amountUpper
      this.amounts[1]['lower'] = '￥' + this.application.amount.toFixed(2)
      // 如果发票项不足5行，填补空白行
      if (this.application.itemList.length < 5) {
        let needEmpty = 5 - this.application.itemList.length
        for (let i = needEmpty; i > 0; i--) {
          let obj = {
            itemId: null,
            fapiaoId: null,
            taxableServiceName: null,
            serviceSpecification: null,
            serviceUnit: null,
            number: null,
            unit: null,
            price: null,
            amount: null,
            taxRate: 0.13,
            taxMoney: null
          }
          this.application.itemList.push(obj)
        }
      }
    })
  }

  async getHeaderListReq() {
    await getFapiaoHeaderApi({ all: false }).then(res => {
      this.headers = res.data
      for (let i = 0; i < this.headers.length; i++) {
        this.headers[i]['value'] = this.headers[i]['taxpayerName']
      }
    })
  }

  customerSelect(item) {
    this.customer[0]['value'] = item.taxpayerName
    this.customer[1]['value'] = item.taxpayerNumber
    this.customer[2]['value'] = item.address + '  ' + item.tel
    this.customer[3]['value'] = item.bank + '  ' + item.account
    this.cacheApplication.header = item
  }
  querySearch(queryString, cb) {
    var headers = this.headers
    var results = queryString ? headers.filter(this.createFilter(queryString)) : headers
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  createFilter(queryString) {
    return header => {
      return header.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    }
  }

  /* 视图控制变量 */
  isEdit: boolean = false
  showReview: boolean = false
  showApproval: boolean = false

  dialogTitle: string = '发票申请审核'
  dialogVisible: boolean = false
  preDdialogVisible: boolean = false

  /* 提交初审数据 */
  submitInput: string = ''
  preAuditor: string = ''
  userList: any = []

  /* 编辑状态下删除发票项 */
  removeItem(index) {
    this.cacheApplication.itemList.splice(index, 1)
    if (this.cacheApplication.itemList.length == 0) {
      this.insertItem(0)
    }
    // 删除后重新合计

    // 计算合计金额（含税）和合计税额
    let total: number = 0
    let totalTax: number = 0
    this.cacheApplication.itemList.forEach(element => {
      total += element.amount * 100
      totalTax += element.taxMoney * 10000
    })
    total = total / 100
    totalTax = totalTax / 10000
    // 金额大写转换
    let moneyUpper = moneyToUpper(total)
    // 绑定请求数据
    this.cacheApplication.amount = total
    this.cacheApplication.amountTax = totalTax
    this.cacheApplication.amountUpper = moneyUpper
    // 绑定视图数据
    this.amounts[0]['titleL'] = '￥' + total
    this.amounts[0]['amountTax'] = '￥' + totalTax
    this.amounts[1]['lower'] = '￥' + total
    this.amounts[1]['upper'] = moneyUpper
  }
  /* 编辑状态下添加发票项 */
  insertItem(index) {
    let obj = {
      itemId: null,
      fapiaoId: null,
      taxableServiceName: '',
      serviceSpecification: '',
      serviceUnit: '',
      number: 1,
      unit: '',
      price: 0,
      amount: 0,
      taxRate: 0.13,
      taxMoney: 0
    }
    this.cacheApplication.itemList.splice(index + 1, 0, obj)
  }
  /* 编辑发票数量项 */
  numberChange(row) {
    if (row.number == 0) {
      this.$alert('数量不能为0').then(() => (row.number = 1))
    } else if (/^[0-9]+([.][0-9]{1,2})?$/.test(row.number)) {
      // 计算单价（含税）如果数除不尽或者小数位数超过6位则保存6位小数
      row.price = Math.round((row.amount / row.number) * 100) / 100
      // 计算税额 
      row.taxMoney = Math.round(((row.amount / (row.taxRate + 1)) * row.taxRate) * 100) / 100
      // 计算合计金额（含税）和合计税额
      let total: number = 0
      let totalTax: number = 0
      this.cacheApplication.itemList.forEach(element => {
        total += element.amount * 100
        totalTax += element.taxMoney * 10000
      })
      total = total / 100
      totalTax = totalTax / 10000
      // 金额大写转换
      let moneyUpper = moneyToUpper(total)
      // 绑定请求数据
      this.cacheApplication.amount = total
      this.cacheApplication.amountTax = totalTax
      this.cacheApplication.amountUpper = moneyUpper
      // 绑定视图数据
      this.amounts[0]['titleL'] = '￥' + total
      this.amounts[0]['amountTax'] = '￥' + totalTax
      this.amounts[1]['lower'] = '￥' + total
      this.amounts[1]['upper'] = moneyUpper
    } else {
      this.$alert('数量请输入整数或1-2位小数', '错误提示')
    }
  }

  /* 编辑发票金额项 */
  amountChange(row) {
    if (/^[0-9]+([.][0-9]{1,2})?$/.test(row.amount)) {
      // 计算 单价 税额
      if (row.amount == 0) {
        row.price = 0
        row.taxMoney = 0
      } else {
        // 计算单价（含税）如果数除不尽或者小数位数超过6位则保存6位小数
        row.price = Math.round((row.amount / row.number) * 100) / 100
        // 计算税额
        row.taxMoney = Math.round(((row.amount / (row.taxRate + 1)) * row.taxRate) * 100) / 100
      }
      // 计算合计金额（含税）和合计税额
      let total: number = 0
      let totalTax: number = 0
      this.cacheApplication.itemList.forEach(element => {
        total += element.amount * 100
        totalTax += element.taxMoney * 10000
      })
      total = total / 100
      totalTax = totalTax / 10000
      // 金额大写转换
      let moneyUpper = moneyToUpper(total)
      // 绑定请求数据
      this.cacheApplication.amount = total
      this.cacheApplication.amountTax = totalTax
      this.cacheApplication.amountUpper = moneyUpper
      // 绑定视图数据
      this.amounts[0]['titleL'] = '￥' + total
      this.amounts[0]['amountTax'] = '￥' + totalTax
      this.amounts[1]['lower'] = '￥' + total
      this.amounts[1]['upper'] = moneyUpper
    } else {
      this.$alert('金额请输入整数或1-2位小数', '错误提示')
    }
  }

  edit() {
    // 判断状态是否可编辑
    if (this.application.state.string == '待提交' || this.application.state.string == '初审未通过') {
      this.cacheApplication = _.cloneDeep(this.application)
      this.isEdit = true
    } else {
      this.$message.warning('不可编辑状态')
    }
  }

  /* ********** ********** */
  /* ****** 保存申请 ****** */
  /* ********** ********** */
  async saveApplicationReq() {
    this.cacheApplication['state'] = null
    this.cacheApplication.itemList = this.cacheApplication.itemList.filter(item => item.taxableServiceName != null)
    await saveFapiaoApplicationApi(this.cacheApplication)
      .then(res => {
        this.$message.success('保存成功')
        this.application.fapiaoId = res.data
        this.getFapiaoApplicationReq().then(() => this.cancel())
      })
      .catch(err => {
        // 出现错误 补齐 5 行
        if (this.cacheApplication.itemList.length < 5) {
          let needEmpty = 5 - this.cacheApplication.itemList.length
          for (let i = needEmpty; i > 0; i--) {
            let obj = {
              itemId: null,
              fapiaoId: null,
              taxableServiceName: null,
              serviceSpecification: null,
              serviceUnit: null,
              number: null,
              unit: null,
              price: null,
              amount: null,
              taxRate: 0.13,
              taxMoney: null
            }
            this.cacheApplication.itemList.push(obj)
          }
        }
      })
  }

  cancel() {
    // 发票抬头信息绑定原数据
    this.customerSelect(this.application.header)
    // 发票合计信息绑定原数据
    this.amounts[0]['titleL'] = '￥' + this.application.amount
    this.amounts[0]['amountTax'] = '￥' + this.application.amountTax
    this.amounts[1]['upper'] = this.application.amountUpper
    this.amounts[1]['lower'] = '￥' + this.application.amount
    // 关闭编辑视图
    this.isEdit = false
  }

  async submit() {
    let params = {
      fapiaoId: this.application.fapiaoId,
      handleConclusion: true,
      handleRemark: this.submitInput,
      next: this.preAuditor
    }
    await submitFapiaoApplicationApi(params).then(res => {
      this.getFapiaoApplicationReq()
      this.closePreDialog()
    })
  }

  /* 显示提交弹框 */
  async pageViewChangeSubmit() {
    // 获取办公人员姓名
    await getUserListApi({ onTheJob: true })
      .catch(err => Notification.error(err))
      .then((res: any) => {
        this.userList = []
        for (let i = 0; i < res.data.length; i++) {
          for (let j = 0; j < res.data[i]['roles'].length; j++) {
            if (res.data[i]['roles'][j].roleName != '工人') {
              this.userList.push(res.data[i].userName)
              break
            }
          }
        }
        this.preDdialogVisible = true
      })
  }

  /* 显示初审弹框 */
  pageViewChangePreAudit() {
    this.dialogTitle = '发票申请初审'
    this.dialogVisible = true
  }

  /* 显示审核弹框 */
  pageViewChangeAudit() {
    this.dialogTitle = '发票申请审核'
    this.dialogVisible = true
  }

  /* 显示批准弹框 */
  pageViewChangeApproval() {
    this.dialogTitle = '发票申请批准'
    this.dialogVisible = true
  }

  /* 关闭审批弹框 */
  closeDialog() {
    this.dialogTitle = ''
    this.dialogVisible = false
  }

  /* 关闭提交弹框 */
  closePreDialog() {
    this.preDdialogVisible = false
  }

  // 审核批准结果
  handleResult: any = {
    handleConclusion: 2,
    handleRemark: ''
  }

  /* ********** ********** */
  /* ****** 审批保存 ****** */
  /* ********** ********** */
  submitForm() {
    if (this.handleResult.handleConclusion == 0 || this.handleResult.handleConclusion == 1) {
      let reqParam = {
        fapiaoId: this.application.fapiaoId,
        handleConclusion: this.handleResult.handleConclusion == 0 ? false : true,
        handleRemark: this.handleResult.handleRemark
      }
      if (this.dialogTitle == '发票申请初审') {
        this.preauditApplicationReq(reqParam)
      } else if (this.dialogTitle == '发票申请审核') {
        this.auditApplicationReq(reqParam)
      } else if (this.dialogTitle == '发票申请批准') {
        this.approvalApplicationReq(reqParam)
      }
      this.handleResult['handleConclusion'] = 2
      this.handleResult['handleRemark'] = ''
      this.closeDialog()
    } else {
      this.$alert('请选择审核结论')
    }
  }
  async preauditApplicationReq(params) {
    await preauditFapiaoApplicationApi(params).then(res => this.getFapiaoApplicationReq())
  }
  async auditApplicationReq(params) {
    await auditFapiaoApplicationApi(params).then(res => this.getFapiaoApplicationReq())
  }
  async approvalApplicationReq(params) {
    await approvalFapiaoApplicationApi(params).then(res => this.getFapiaoApplicationReq())
  }

  /* ********** ********** */
  /* **** 关闭申请流程 **** */
  /* ********** ********** */
  closeApplication() {
    this.$prompt('请输入操作备注', `关闭申请流程`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then((value: any) => {
        this.closeApplicationReq(value)
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
  }
  async closeApplicationReq(value) {
    await closeFapiaoApplicationApi({
      fapiaoId: this.application.fapiaoId,
      handleConclusion: true,
      handleRemark: value.value
    }).then(res => this.getFapiaoApplicationReq())
  }

  /* 返回上级页面 */
  back() {
    this.$router.go(-1)
  }

  /* 发票抬头表格单元格合并 */
  mergeA({ row, column, rowIndex, columnIndex }) {
    if (columnIndex === 1) {
      return {
        rowspan: 1,
        colspan: 9
      }
    }
  }

  /* 发票合计表格单元格合并 */
  mergeB({ row, column, rowIndex, columnIndex }) {
    if (rowIndex === 0) {
      if (columnIndex === 1) {
        return {
          rowspan: 1,
          colspan: 4
        }
      }
    } else {
      if (columnIndex === 1) {
        return {
          rowspan: 1,
          colspan: 4
        }
      }
      if (columnIndex === 3) {
        return {
          rowspan: 1,
          colspan: 4
        }
      }
    }
  }
}
</script>

<style>
.el-col {
  border: 1px solid transparent;
}

.btn5 {
  float: right;
  margin-right: 20px;
}

.header-cell-style {
  color: #000000;
  font-weight: bold;
  border: 1px solid black;
  background-color: #ffffff;
}

.cell-style {
  height: 48px;
  line-height: 48px;
  border: 1px solid black;
}

.amount-cell-style {
  font-weight: bold;
  border: 1px solid black;
}
</style>
